<template>
  <div class="earth" :class="{full: isFull}">
    <div class="earth-inner" ref="main"></div>

    <div class="earth-tool">
     <div class="earth-tool-item">
       <i class="el-icon-full-screen"  @click="isFull = !isFull"></i>
     </div>
    </div>
    <div class="earth-tip" v-show="jd && wd">
      <span>{{$t('坐标')}}: {{jd}}, {{wd}}</span>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
// window.CESIUM_BASE_URL = '/';
// import * as Cesium from 'cesium'
// import 'cesium/Build/Cesium/Widgets/widgets.css'
import bus from '$ui/utils/bus'
import {getUserFromCache} from '@/helper/utils'
import {publicPath} from '@/constant';

export default {
  name: 'earth',
  cnName: 'earth',
  props: {
    // Your access token can be found at: https://cesium.com/ion/tokens.
    // Replace `your_access_token` with your Cesium ion access token.
    token: {
      type: String,
      default: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiNGQzZDBlYi0wOGZmLTQ1ZjEtOTcxYS0zZjllYmE4NzZkZWYiLCJpZCI6Nzc2NjYsImlhdCI6MTY0NTk3NjkxOH0.Elg7CMqcvzrx1SCrx7If92g2z62IefUtkq6oZKvvnbg'
    },
    billBoards: {
      type: Array
    }
  },
  data() {
    const user = getUserFromCache()
    let isVisitor = false
    if (user && user.user) {
      if(user.user.roleIdList && user.user.roleIdList.length === 1) {
        isVisitor = user.user.roleIdList[0] === 2
      }
    }

    return {
      isVisitor,
      entityList: [],
      jd: '',
      wd: '',
      isFull: false
    }
  },
  methods: {
    onMax() {
      this.isFull = true
    },
    onMin() {
      this.isFull = false
    },
    init() {
      // 默认显示中国
      Cesium.Ion.defaultAccessToken = this.token;
      Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);

      const viewer = this.viewer = new Cesium.Viewer(this.$refs.main, {
        orderIndependentTranslucency: false,
        contextOptions: {
          webgl: {
            alpha: true,
          }
        },
        selectionIndicator: false,
        animation: false,  // 是否显示动画控件
        baseLayerPicker: true, // 是否显示图层选择控件
        geocoder: false, // 是否显示地名查找控件
        timeline: false, // 是否显示时间线控件
        sceneModePicker: true, // 是否显示投影方式控件
        navigationHelpButton: false, // 是否显示帮助信息控件
        infoBox: false,  // 是否显示点击要素之后显示的信息
        fullscreenButton: true
      })

      viewer.scene.skyBox.show = false;
      viewer.scene.backgroundColor = new Cesium.Color(0.0, 0.0, 0.0, 0.0);

      // 谷歌影像标注图
      viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        url: "http://mt1.google.cn/vt/lyrs=y&hl=EN&x={x}&y={y}&z={z}&s=Gali"
      }))
      // Add Cesium OSM Buildings, a global 3D buildings layer.
      const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());
      const handlerVideo = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handlerVideo.setInputAction((event) => {
        // var earthPosition  = viewer.camera.pickEllipsoid(event.position,viewer.scene.globe.ellipsoid);
        // var cartographic = Cesium.Cartographic.fromCartesian(earthPosition, viewer.scene.globe.ellipsoid, new Cesium.Cartographic());
        // var lat=Cesium.Math.toDegrees(cartographic.latitude);
        // var lng=Cesium.Math.toDegrees(cartographic.longitude);
        // var height=cartographic.height;
        // console.log(`经度：${lng}，纬度：${lat}，高度：${height}`);
        const pick = viewer.scene.pick(event.position);
        if (pick && pick.id) {
          const name = pick.id._name
          const item = this.billBoards.find(o => o.name === name)
          if(item) {
          //  this.$router.push('/page/project/' + item.id)
            this.flyto({jd: item.lng, wd: item.lat})
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

      handlerVideo.setInputAction((event) => {
        const pick = viewer.scene.pick(event.position);
        if (pick && pick.id) {
          const name = pick.id._name
          const item = this.billBoards.find(o => o.name === name)
          if(item) {
            if(this.isVisitor) {
              return
            }
             this.$router.push('/page/project/' + item.id)
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)

      var ellipsoid= this.viewer.scene.globe.ellipsoid
      handlerVideo.setInputAction((movement) => {
          //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
          var cartesian=viewer.camera.pickEllipsoid(movement.endPosition, ellipsoid);
          if(cartesian){
            //将笛卡尔三维坐标转为地图坐标（弧度）
            var cartographic=viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
            //将地图坐标（弧度）转为十进制的度数
            var lat_String=Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
            var log_String=Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
            var alti_String=(viewer.camera.positionCartographic.height/1000).toFixed(2);

            this.jd = log_String
            this.wd = lat_String

          }
        },Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      this.addMarkers()
    },
    addMarkers() {
      this.viewer.entities.removeAll()
      this.entityList = []
      this.billBoards.forEach(item => {
        this.addBillboard(item)
      })
    },
    addBillboard(options) {
      const { name, lng, lat, text, img } = options

      const image = img || publicPath + '/img/location.png'
      const entity = this.viewer.entities.add({
        name: name,
        position: Cesium.Cartesian3.fromDegrees(lng, lat),
        label: { // 文字标签
          text: text || '',
          font: '500 30px Helvetica',// 15pt monospace
          scale: 0.5,
          style: Cesium.LabelStyle.FILL,
          fillColor: Cesium.Color.WHITE,
          pixelOffset: new Cesium.Cartesian2(-8, -35),   // 偏移量
          showBackground: true,
          backgroundColor: new Cesium.Color(0.5, 0.6, 1, 1.0),
          borderRadius: 2
        },
        billboard: { // 图标
          image: image,
          width: 22,
          height: 30
        }
      })
      this.entityList.push(entity)
    },
    flyto(data) {
      if(!this.viewer || !data) {
        return
      }
      const {jd, wd} = data
      console.info(jd, wd)
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(jd, wd, 200.0),
      });
    }
  },
  watch: {
    billBoards(){
      this.addMarkers()
    }
  },
  mounted() {
    this.init()
    bus.$on('flyto', this.flyto)
  }
}
</script>

<style lang="scss" scoped>
.earth {
  position: relative;
  height: 100%;
  width: 100%;

  &.full {
    position: fixed;
    left: 0;
    top: 0;
    background: #01114d;
    z-index: 999;
  }

  &-tool {
    position: absolute;
    top: 7px;
    right: 120px;
    color: #FFF;
    z-index: 9;

    &-item {
      box-sizing: border-box;
      width: 32px;
      height: 32px;
      border-radius: 14%;
      padding: 0;
      vertical-align: middle;
      z-index: 0;
      display: inline-block;
      position: relative;
      background: #303336;
      border: 1px solid #444;
      color: #edffff;
      fill: #edffff;
      text-align: center;
      line-height: 30px;
      font-size: 18px;
      cursor: pointer;
    }
  }

  &-inner {
    position: relative;
    height: 100%;
    width: 100%;
  }

  &-tip {
    position: absolute;
    bottom: 20px;
    right: 20px;
  }

  /deep/ {
    .cesium-widget-credits {
      display: none;
    }
    .cesium-viewer-fullscreenContainer {
      display: none !important;
    }
  }
}
</style>
